package sample.api;

import org.dreamwork.misc.Base64;
import org.dreamwork.secure.IKeyFetcher;
import org.dreamwork.secure.KeyFetcherFactory;
import org.dreamwork.util.StringUtil;

import java.io.*;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.cert.X509Certificate;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;
import java.security.spec.PKCS8EncodedKeySpec;

/**
 * Created by IntelliJ IDEA.
 * User: seth.yang
 * Date: 2014/12/11
 * Time: 17:53
 */
public class FileKeyFetcherFactory extends KeyFetcherFactory {
    @Override
    public IKeyFetcher getKeyFetcher () {
        return new FileKeyFetcher ();
    }

    public static class FileKeyFetcher implements IKeyFetcher {
        @Override
        public PrivateKey getPrivateKey (String issuer) throws NoSuchAlgorithmException, InvalidKeySpecException {
            byte[] buff = null;

            File file = new File ("d:/tmp/keys/pkcs8_rsa_private_key.pem");
            FileReader fr = null;
            try {
                fr = new FileReader (file);
                BufferedReader reader = new BufferedReader (fr);
                String line;
                StringBuilder builder = new StringBuilder ();
                while ((line = reader.readLine ()) != null) {
                    line = line.trim ();
                    if (line.startsWith ("--") || StringUtil.isEmpty (line)) continue;

                    builder.append (line);
                }
                buff = Base64.decode (builder.toString ().getBytes ("utf-8"));
            } catch (IOException ex) {
                //
            } finally {
                if (fr != null) try {
                    fr.close ();
                } catch (IOException e) {
                    e.printStackTrace ();
                }
            }

            if (buff != null) {
                KeyFactory factory = KeyFactory.getInstance ("RSA");
                KeySpec spec = new PKCS8EncodedKeySpec (buff);
                return factory.generatePrivate (spec);
            } else {
                return null;
            }
        }

        @Override
        public PublicKey getPublicKey (String issuer) {
            return null;
        }

        @Override
        public X509Certificate getCertificate (String issuer) {
            return null;
        }
    }
}